package ruifeng.zcj.communcationring.base;

import android.graphics.Bitmap;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.View;
import android.webkit.GeolocationPermissions;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jakewharton.rxbinding.view.RxView;
import com.rey.material.widget.ProgressView;

import butterknife.Bind;
import ruifeng.zcj.communcationring.R;
import ruifeng.zcj.communcationring.base.eventbus.EventCenter;

/**
 * Created by Administrator on 2016/8/16 0016.
 */
public abstract class WebViewFragment extends BaseFragment implements
        SwipeRefreshLayout.OnRefreshListener {

    @Bind(R.id.layoutLoading)
    LinearLayout layoutLoading;


    @Bind(R.id.layoutContent)
    LinearLayout mLayoutContent;

    @Bind(R.id.layoutLoadFailed)
    LinearLayout layoutLoadFailed;
    @Bind(R.id.layoutEmpty)
    LinearLayout layoutEmpty;
    @Bind(R.id.progress)
    ProgressView mProgress;
    @Bind(R.id.webview)
    public WebView mWebview;
    @Bind(R.id.txtLoadFailed)
    TextView mTxtLoadFailed;
    @Bind(R.id.txtLoadEmpty)
    TextView mTxtLoadEmpty;
    @Bind(R.id.txtLayoutReload)
    TextView mTxtLayoutReload;

    @Bind(R.id.refreshLayout)
    SwipeRefreshLayout swipeRefreshLayout;

    public WebSettings ws;

    // 初始化的工作
    @Override
    protected void initFragmentConfig() {
        showLoadingDialog("正在加载");
        ws = mWebview.getSettings();
        ws.setJavaScriptEnabled(true);

        if (isCacheMode()) {// 是否设置缓存
            //  ws.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);  //设置 缓存模式(true);
        }
        ws.setAppCacheEnabled(true);
        ws.setSupportZoom(false);
        ws.setUseWideViewPort(true);// 可任意比例缩放
        ws.setJavaScriptCanOpenWindowsAutomatically(true);//js支持
        //启用地理定位
        ws.setGeolocationEnabled(true);
        ws.setDomStorageEnabled(true);

        mWebview.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return WebViewFragment.this.shouldOverrideUrlLoading(view, url);
            }

            /***
             * 判断有网络情况下，页面出错误了才会调用这个方法
             * */
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                dismissLoadingDialog();
                if (errorCode == -2) {
                    layoutLoadFailedVisibility(true);
                    Toast.makeText(App.getAppContext(), "加载数失败 ,请连重启。", Toast.LENGTH_SHORT).show();
                } else {// 失败-10
                    layoutEmptyVisibility(true);
                    Toast.makeText(App.getAppContext(), "网速较慢 ,请刷新。", Toast.LENGTH_SHORT).show();
                }
                view.setVisibility(View.INVISIBLE);
            }


            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                if (mProgress != null) {
                    mProgress.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                dismissLoadingDialog();
                if (mProgress != null) {
                    mProgress.setVisibility(View.GONE);
                }
                if (isRefreshing()) {
                    hideSwipeRefreshing();
                }
                layoutLoadingVisibility(false);
            }
        });
        mWebview.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress < 100) {
                    if (mProgress != null) {
                        mProgress.setVisibility(View.VISIBLE);
                    }

                } else if (newProgress == 100) {
                    if (mProgress != null) {
                        mProgress.setVisibility(View.GONE);
                    }
                }
                if (mProgress != null) {
                    mProgress.setProgress(newProgress);
                }
                super.onProgressChanged(view, newProgress);
            }

            @Override
            public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
                callback.invoke(origin, true, false);
                super.onGeolocationPermissionsShowPrompt(origin, callback);
            }
        });


        swipeRefreshLayout.setOnRefreshListener(this);
        swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);


    }


    @Override
    protected int getContentView() {
        return R.layout.activity_main;
    }


    // 加载数据
    @Override
    protected void onFirstUserVisible() {
        if (mWebview != null) {
            //取消滚动条
            mWebview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
            //触摸焦点起作用
            mWebview.requestFocus();
            mWebview.loadUrl(getURL());

        }
    }

    public String getURL() {
        if (!TextUtils.isEmpty(LoadUrl())) {
            return LoadUrl();
        } else {
            layoutLoadFailedVisibility(false);
            layoutEmptyVisibility(true);
            layoutContentVisibility(false);
            layoutLoadingVisibility(false);
        }
        return null;
    }

    protected abstract String LoadUrl();

    public abstract boolean shouldOverrideUrlLoading(WebView view, String url);


    //  切换到该Fragment  onResume方法   从其他地方来到这个Fragment该做什么事情
    @Override
    protected void onUserVisible() {

    }

    // 切换到其他Fragment
    @Override
    protected void onUserInvisible() {

    }


    public void layoutLoadingVisibility(boolean isVisible) {
        if (layoutLoading != null) {
            RxView.visibility(layoutLoading, View.GONE).call(isVisible);
        }
    }

    public void layoutContentVisibility(boolean isVisible) {
        if (mLayoutContent != null) {
            RxView.visibility(mLayoutContent, View.GONE).call(isVisible);
        }
    }

    public void layoutLoadFailedVisibility(boolean isVisible) {
        if (layoutLoadFailed != null) {
            RxView.visibility(layoutLoadFailed, View.GONE).call(isVisible);
        }
    }

    public void layoutEmptyVisibility(boolean isVisible) {
        if (layoutEmpty != null) {
            RxView.visibility(layoutEmpty, View.GONE).call(isVisible);
        }
    }

    public void showSwipeRefreshing() {
        if (swipeRefreshLayout != null) {
            swipeRefreshLayout.setRefreshing(true);
        }
    }

    public void hideSwipeRefreshing() {
        if (swipeRefreshLayout != null) {
            swipeRefreshLayout.setRefreshing(false);
        }
    }

    public boolean isRefreshing() {
        if (swipeRefreshLayout != null) {
            return swipeRefreshLayout.isRefreshing();
        }
        return false;
    }


    @Override
    public void onRefresh() {
        if (mWebview != null) {
            mWebview.reload();
            layoutLoadFailedVisibility(false);
            layoutEmptyVisibility(false);
            layoutContentVisibility(true);
            layoutLoadingVisibility(true);
            mWebview.setVisibility(View.VISIBLE);
        }
    }


    public void onEventMainThread(EventCenter event) {
        String msg = "onEventMainThread收到了消息：" + event.getValue();
        Toast.makeText(App.getAppContext(), msg, Toast.LENGTH_LONG).show();
    }

    @Override
    protected void cleanMemory() {
        if (mWebview != null) {
            mWebview.removeAllViews();
            mWebview.destroy();
        }
    }

    public boolean isCacheMode() {
        return true;
    }



}
